package com.example.interceptor;

import com.example.result.ReturnCode;
import com.example.result.ReturnResult;
import com.example.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        if(!StringUtils.hasLength(token)){
            returnNotLogin(response);
            return false;
        }

        try{
            JwtUtils.parseJwt(token);
        } catch (Exception e) {
            returnNotLogin(response);
            return false;
        }

        return true;
    }

    private void returnNotLogin(HttpServletResponse response) throws IOException {
        ReturnResult result=new ReturnResult(ReturnCode.LOGIN_FAIL,"未登录");
        ObjectMapper objectMapper=new ObjectMapper();
        String json=objectMapper.writeValueAsString(result);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}

